04_01 Components
Components
Components help you organize a complex project into smaller pieces. It helps you build reusable items.
Creating Components
const App = Vue.createApp({})
App.component('name', { template: `template` })
App.mount('#App')
<div id="App"><name></name></div>
To create a component, you have to split up our app into two parts, creating the app and mounting the app.
That why, we can use the component method to create a component. You pass along the name of the component, which becomes the name of a tag you can use in the HTML that calls this component.
The components become reusable instances, so you can use them as many times as you want.
Component Options
data
computed
watch
methods
lifecycle hooks
- can be nested
global
orlocal
registration
You can also use almost every method that you can inside a regular app.
Components can also be used...or nested inside other components.
They can also be added as global components, which is what we did with the previous component, but you can also register them locally.
Receiving Props
App.component('myComponent', {
props: ['myProp'],
template: ``
})
<my-component my-prop="myValue"></my-component>
Of course, that button wouldn't be particularly useful without some options, to pass along some information to a component, we use props, which is a shorthand for properties. They look like HTML tag properties and pass along a value to the component
Notice that although the props name in the script is in camel case, you can use it in the template as kebob case with the hyphens and lowercase.
Binding Props
const App = Vue.createApp({
data() { return { myVar: 'myValue' } }
})
App.component('myComponent', {
props: ['myProp'], template: ``
})
App.mount('#App')
<my-component :my-prop="myVar"></my-component>
Passing along hard-coded values isn't always optimal, sometimes you want to pass a along a series of values and you can do that using v-bind, of course you can use the colon shortcut and pass along a variable name from the data section.
Practice
- Rewrite
App
calls - Create
Currency
Component - Replace template calls
For this exercise, we'll need to modify the application so that it will work with components, so we'll need to separate the creation from the mounting of the app.
Then we're going to recreate the currency method into it's own component
Finaly, we'll replace method calls in our template.
The advantage to putting things in components is that they're reusable and help you organize code into logical pieces.